"""
简化的Flask示例演示
不依赖复杂的工具包导入，直接展示Flask功能
"""

try:
    from flask import Flask, request, jsonify
    import json
    import os
    from datetime import datetime
    
    app = Flask(__name__)
    
    # 简单的内存存储
    users = []
    articles = []
    
    @app.route('/')
    def home():
        return jsonify({
            'message': '欢迎使用Python Backend Toolkit Flask示例',
            'timestamp': datetime.now().isoformat(),
            'endpoints': {
                'GET /': '首页',
                'GET /users': '获取用户列表',
                'POST /users': '创建用户',
                'GET /articles': '获取文章列表',
                'POST /articles': '创建文章',
                'GET /health': '健康检查'
            }
        })
    
    @app.route('/users', methods=['GET'])
    def get_users():
        return jsonify({
            'success': True,
            'users': users,
            'count': len(users)
        })
    
    @app.route('/users', methods=['POST'])
    def create_user():
        data = request.get_json()
        if not data or 'name' not in data:
            return jsonify({'success': False, 'message': '缺少用户名'}), 400
        
        user = {
            'id': len(users) + 1,
            'name': data['name'],
            'email': data.get('email', ''),
            'created_at': datetime.now().isoformat()
        }
        users.append(user)
        
        return jsonify({
            'success': True,
            'message': '用户创建成功',
            'user': user
        }), 201
    
    @app.route('/articles', methods=['GET'])
    def get_articles():
        return jsonify({
            'success': True,
            'articles': articles,
            'count': len(articles)
        })
    
    @app.route('/articles', methods=['POST'])
    def create_article():
        data = request.get_json()
        if not data or 'title' not in data:
            return jsonify({'success': False, 'message': '缺少文章标题'}), 400
        
        article = {
            'id': len(articles) + 1,
            'title': data['title'],
            'content': data.get('content', ''),
            'author': data.get('author', 'Anonymous'),
            'created_at': datetime.now().isoformat()
        }
        articles.append(article)
        
        return jsonify({
            'success': True,
            'message': '文章创建成功',
            'article': article
        }), 201
    
    @app.route('/health')
    def health_check():
        return jsonify({
            'status': 'healthy',
            'service': 'Flask简化示例',
            'timestamp': datetime.now().isoformat(),
            'stats': {
                'users': len(users),
                'articles': len(articles)
            }
        })
    
    if __name__ == '__main__':
        print("🚀 启动Flask简化示例")
        print("📝 功能:")
        print("   - 用户管理 (GET/POST /users)")
        print("   - 文章管理 (GET/POST /articles)")
        print("   - 健康检查 (GET /health)")
        print()
        print("🌐 访问: http://localhost:5000")
        print("📖 API文档: http://localhost:5000/")
        print()
        print("💡 测试命令:")
        print("   curl http://localhost:5000/")
        print("   curl -X POST -H 'Content-Type: application/json' -d '{\"name\":\"张三\",\"email\":\"zhang@example.com\"}' http://localhost:5000/users")
        print("   curl -X POST -H 'Content-Type: application/json' -d '{\"title\":\"测试文章\",\"content\":\"这是一篇测试文章\"}' http://localhost:5000/articles")
        print()
        
        app.run(host='0.0.0.0', port=5000, debug=True)

except ImportError as e:
    print(f"❌ 导入错误: {e}")
    print("请确保已安装Flask:")
    print("pip install flask")
    
except Exception as e:
    print(f"❌ 运行错误: {e}")